package com.aopcinemas.cinema.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.aopcinemas.cinema.model.Movie;
import com.aopcinemas.cinema.model.Movie.AgeConstraint;
import com.aopcinemas.cinema.model.Movie.Genre;

public class MovieDao {

    private Connection connection;

    public MovieDao(Connection connection) {
        this.connection = connection;
    }

    public List<Movie> getMovies() {
        List<Movie> movies = new ArrayList<Movie>();

        try {
            Statement st = connection.createStatement();
            ResultSet rs = st.executeQuery("select * from movie");
            while (rs.next()) {
                Movie movie = new Movie();
                movie.setId(rs.getLong("id"));
                movie.setName(rs.getString("name"));
                movie.setDescription(rs.getString("description"));
                movie.setDuration(rs.getLong("duration"));
                movie.setGenre(Genre.valueOf(rs.getString("genre")));
                movie.setAgeConstraint(AgeConstraint.valueOf(rs.getString("age_constraint")));
                movies.add(movie);
            }

            rs.close();
            st.close();
        } catch (SQLException e) {
            throw new RuntimeException("System error", e);
        }
        return movies;
    }

    public void addMovie(Movie movie) {
        try {
            Statement st = connection.createStatement();
            int rows = st.executeUpdate("insert into movie(name, description, genre, duration, age_constraint) values('" + movie.getName() + "', '" + movie.getDescription() + "', '" + movie.getGenre().toString() + "', " + movie.getDuration() + " , '" + movie.getAgeConstraint().toString() + "' )");
            if (rows <= 0) {
                throw new RuntimeException("Can't add movie to database");
            }
            st.close();
        } catch (SQLException e) {
            throw new RuntimeException("System error", e);
        }
    }
}
